import json
import re
import chardet
import requests
from django.http import JsonResponse
from django.shortcuts import render


# Create your views here.

def search_list(request):
    print(request.GET)
    query = request.GET.get('q')
    try:
        response = requests.get(
            "https://so.csdn.net/api/v3/search",
            params={
                'q': query,
                't': 'all',
                'p': '2',
                's': '0',
                'tm': '0',
                'lv': '-1',
                'ft': '0',
                'l': '',
                'u': '',
                'ct': '-1',
                'pnt': '-1',
                'ry': '-1',
                'ss': '-1',
                'dct': '-1',
                'vco': '-1',
                'cc': '-1',
                'sc': '-1',
                'akt': '-1',
                'art': '-1',
                'ca': '-1',
                'prs': '',
                'pre': '',
                'ecc': '-1',
                'ebc': '-1',
                'ia': '1',
                'dId': '',
                'cl': '-1',
                'scl': '-1',
                'tcl': '-1',
                'platform': 'pc',
                'ab_test_code_overlap': '',
                'ab_test_random_code': '',
            }
        )
        detected_enc = chardet.detect(response.content)['encoding']
        response.encoding = detected_enc if detected_enc else 'utf-8'
        response = response.text.replace(u'\xa0', u' ')
        search_data = json.loads(response)
        search_data = search_data['result_vos']
        result = []
        for blog in search_data:
            author = blog['nickname']
            title = blog['title']
            description = blog['description']
            # img_url = blog['pic_list'][0]
            blog_id = blog['id']
            pattern = re.compile(r'(</?em>)')
            author = pattern.sub('', author)
            title = pattern.sub('', title)
            description = pattern.sub('', description)
            blog_url = blog['url']
            json_data = {
                'author': author,
                'title': title,
                "description": description,
                # "img_url": img_url,
                'blog_id': blog_id,
                'blog_url': blog_url
            }
            result.append(json_data)

        return render(request, 'search/search_list.html', context={
            'query': query,
            'data': result
        })
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
